<template>
    <div class='approval'>
        <el-card class="box-card" style="margin-top: 110px;">
            <div class='title'>
                {{$t('approvalDispatch.title1')}}
            </div>
            <div class='menu-search'> 
                <div class='menu-title'>
                    <!-- 业务ID -->
                    <div class='searchItem'>
                        <span>{{$t('lenders.orderId')}}</span>
                        <el-input v-model='listQuery.orderId' :placeholder="$t('rule.orderId')" size='small'></el-input>
                    </div>
                    <!-- 客户姓名 -->
                    <div class='searchItem'>
                        <span>{{$t('lenders.realName')}}</span>
                        <el-input v-model='listQuery.realName' :placeholder="$t('rule.realName')" size='small'></el-input>
                    </div>
                    <!-- 手机号 -->
                    <div class='searchItem'>
                        <span>{{$t('lenders.phoneNo')}}</span>
                        <el-input v-model='listQuery.mobile' :placeholder="$t('rule.phoneNo')" size='small'></el-input>
                    </div>
                    <!-- 分账状态 -->
                    <div class='searchItem'>
                        <span>{{$t('orderDivision.divisionStatus')}}</span>
                        <el-select v-model='listQuery.subAccountSatus' size='small'>
                            <el-option
                            v-for='item in divStatus'
                            :key='item.value'
                            :label='item.label'
                            :value='item.value'>
                            </el-option>
                        </el-select>
                    </div>
                    <!-- 业务渠道 -->
                    <div class='searchItem'>
                        <span>{{$t('customQuery.channel')}}</span>
                        <el-select v-model='listQuery.channel' size='small'>
                            <el-option
                            v-for='item in business'
                            :key='item.channel'
                            :label='item.org_name'
                            :value='item.channel'>
                            </el-option>
                        </el-select>
                    </div>
                    <!-- 还款时间 -->
                    <div class='searchItem searchItem-date'>
                        <span>{{$t('approvalDetail.realRepayDate')}}</span>
                        <el-date-picker
                        size='small'
                        class="dates"
                        v-model="listQuery.sepaymentTimeStart"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :placeholder="$t('rule.beginDate')">
                        </el-date-picker>
                        <b>{{$t('lenders.go')}}</b>
                        <el-date-picker
                        size='small'
                        class="dates"
                          v-model="listQuery.sepaymentTimeEnd"
                          type="date"
                          value-format="yyyy-MM-dd"
                          :placeholder="$t('rule.endDate')">
                        </el-date-picker>
                    </div>
                </div>
                <div class='menu-title-btn'>
                  <button type='button' @click='search'>
                      {{$t('btn.query')}}
                  </button>
                  <button type='button' @click='reset'>
                      {{$t('btn.reset')}}
                  </button>
                  <button type='button' @click="handleDownload" :disabled="expDis" v-if="orderDivision_btn_export">
                      {{$t('btn.export')}}
                  </button>
              </div>
            </div>
        </el-card>
        <el-card class='box-card' style="margin-top: 10px;margin-bottom: 20px;">
            <div class='title'>
                {{$t('approvalDispatch.title2')}}
            </div>
            <el-table
                v-loading="listLoading"
                ref='multipleTable'
                :data='tableData'
                tooltip-effect='dark'
                style='width: 100%'
                @selection-change='handleSelectionChange'
                border
                size='mini'>
                <!-- 业务ID -->
                <el-table-column
                prop='orderId' align="center" header-align="center" 
                :label="$t('approvalDispatch.orderId')"
                width='140'
                fixed="left">
                </el-table-column>
                <!-- 客户姓名 -->
                <el-table-column
                prop='realName' align="center" header-align="center" 
                :label="$t('approvalDispatch.realName')"
                width='140'>
                </el-table-column>
                <!-- 手机号 -->
                <el-table-column
                prop='mobile' align="center" header-align="center" 
                :label="$t('approvalDispatch.phoneNo')"
                width='140'>
                </el-table-column>
                <!-- 产品名称 -->
                <el-table-column
                prop='productName' align="center" header-align="center" 
                :label="$t('approvalDispatch.proName')"
                width='140'>
                </el-table-column>
                <!-- 实收金额 -->
                <el-table-column
                prop='price' align="center" header-align="center" 
                :label="$t('RushReport.actualAmt')"
                width='140'>
                </el-table-column>
                <!-- 分账状态 -->
                <el-table-column
                prop='subAccountSatus' align="center" header-align="center" 
                :label="$t('orderDivision.divisionStatus')"
                width='140'>
                <template slot-scope="scope">
                  <span v-if="scope.row.subAccountSatus=== '1'">{{$t('orderDivision.waitDivision')}}</span>
                  <span v-if="scope.row.subAccountSatus=== '2'">{{$t('orderDivision.alDivision')}}</span>
              </template>
                </el-table-column>
                <!-- 还款时间 -->
                <el-table-column
                prop='repaymentTime' align="center" header-align="center" 
                :label="$t('approvalDetail.realRepayDate')"
                width='140'>
                </el-table-column>
                <!-- 业务渠道 -->
                <el-table-column
                prop='channel' align="center" header-align="center" 
                :label="$t('approval.channel')"
                width='140'>
                </el-table-column>
                <!-- 分账本金 -->
                <el-table-column
                prop='subEctionPrincipal' align="center" header-align="center" 
                :label="$t('orderDivision.divCapital')"
                width='140'>
                </el-table-column>
                <!-- 分账罚息 -->
                <el-table-column
                prop='repaymentOverduePenalty' align="center" header-align="center" 
                :label="$t('orderDivision.divInterest')"
                width='140'>
                </el-table-column>
                <!-- 分账利息 -->
                <el-table-column
                prop='repaymentOverdueInterest' align="center" header-align="center" 
                :label="$t('orderDivision.divInterestRate')"
                width='140'>
                </el-table-column>
                <el-table-column
                fixed="right"
                :label="$t('user.operation')"
                width="90"
                header-align="center"
                align="center">
                <template slot-scope="scope">
                    <!-- 分账 -->
                    <el-button
                    v-if="scope.row.subAccountSatus=== '1'"
                    type="primary"
                    size="mini"
                    @click="handleDivision(scope.$index, scope.row)">{{$t('orderDivision.division')}}</el-button>
                </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="listQuery.page"
              :page-sizes="[5, 10, 20, 30]"
              :page-size="listQuery.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
              </el-pagination>
            </div>
        </el-card>
        <el-dialog :title="$t('orderDivision.divOperation')" :visible.sync="dialogFormVisible">
            <div class="part-table">
              <!-- 业务ID -->
              <div class="part-item">
                <div>{{$t('approval.orderId')}}</div>
                <div>{{partTable.orderId}}</div>
              </div>
              <!-- 实收金额 -->
              <div class="part-item">
                <div>{{$t('RushReport.actualAmt')}}</div>
                <div>{{price}}</div>
              </div>
              <!-- 分账本金 -->
              <div class="part-item">
                <div>{{$t('orderDivision.divCapital')}}</div>
                <div><input type="number" v-model="partTable.subEctionPrincipal" class="inp" onkeyup="value=value.replace(/\-/g,'')" :placeholder="$t('rule.inp')"></div>
              </div>
              <!-- 分账罚息 -->
              <div class="part-item">
                <div>{{$t('orderDivision.divInterest')}}</div>
                <div><input type="number" v-model="partTable.repaymentOverduePenalty" class="inp" onkeyup="value=value.replace(/\-/g,'')" :placeholder="$t('rule.inp')"></div>
              </div>
              <!-- 分账利息 -->
              <div class="part-item">
                <div>{{$t('orderDivision.divInterestRate')}}</div>
                <div><input type="number" v-model="partTable.repaymentOverdueInterest" class="inp" onkeyup="value=value.replace(/\-/g,'')" :placeholder="$t('rule.inp')"></div>
              </div>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="cancel">{{$t('btn.cancel')}}</el-button>
                <el-button type="primary" @click="conserveFn">{{$t('btn.conserve')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import { dataMasking } from 'utils/index';
import { page, subAccount, pageExport } from 'api/collection/orderDivision/index'
import { getChannels } from 'api/customQuery/index'
export default {
  data() {
    return {
      orderDivision_btn_export: false,
      partTable: {
        orderId: '',
        subEctionPrincipal: '',
        repaymentOverduePenalty: '',
        repaymentOverdueInterest: '',
        payWaterId: ''
      },
      price: '',
      listLoading: false,
      total: null,
      listQuery: {
        limit: 5,//每页条数
        page: 1,//当前页数
        orderId: "",//订单号
        realName: "",//姓名
        mobile: "",//手机
        sepaymentTimeStart: "",
        sepaymentTimeEnd: "",
        subAccountSatus: "",//分账状态
        channel: "",
      },
      tableData: [],
      multipleSelection: [],
      dialogFormVisible: false,
      expDis: true,
      divStatus: [
        {
          value: '',
          label: this.$t('rule.all')
        },
        {
          value: 1,
          label: this.$t('orderDivision.waitDivision')
        },
        {
          value: 2,
          label: this.$t('orderDivision.alDivision')
        }
      ],
      business: []
    };
  },
  computed: {
    ...mapGetters(["elements", "orderDivisionPage"])
  },
  created() {
    if (this.orderDivisionPage.has(this.$route.path)) {
      this.listQuery = this.orderDivisionPage.get(this.$route.path)
    }
    //渠道下拉
    getChannels()
    .then(response => {
      this.business = response.data;
    })
    this.getList();
    this.orderDivision_btn_export = this.elements['orderDivision:btn_export'];
  },
  methods: {
    //点击分账
    handleDivision(index, row) {
      this.partTable.orderId = row.orderId;
      this.partTable.payWaterId = row.payWaterId;
      this.price = row.price;
      this.dialogFormVisible = true
    },
    // 点击导出
    handleDownload() {
      this.listLoading = true;
      pageExport(this.listQuery)
      .then(response => {
        response.data.forEach(item => {
          if (item.realName || item.mobile) {
            item.realName = dataMasking(item.realName)
            item.mobile = dataMasking(item.mobile)
          }
          if (item.subAccountSatus === '1') {
            item.subAccountSatus = this.$t('orderDivision.waitDivision')
          } else if (item.subAccountSatus === '2'){
            item.subAccountSatus = this.$t('orderDivision.alDivision')
          }
        })
        require.ensure([], () => {
          const { export_json_to_excel } = require('@/vendor/Export2Excel')
          const tHeader = [ this.$t('approvalDispatch.orderId'), this.$t('approvalDispatch.realName'), this.$t('approvalDispatch.phoneNo'), this.$t('approvalDispatch.proName'), this.$t('RushReport.actualAmt'), this.$t('orderDivision.divisionStatus'), this.$t('approvalDetail.realRepayDate'), this.$t('approval.channel'), this.$t('orderDivision.divCapital'), this.$t('orderDivision.divInterest'), this.$t('orderDivision.divInterestRate')];
          const filterVal = [ 'orderId', 'realName', 'mobile', 'productName', 'price', 'subAccountSatus', 'repaymentTime', 'channel', 'subEctionPrincipal', 'repaymentOverduePenalty', 'repaymentOverdueInterest'];
          const list = response.data;
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, this.$t('route.orderDivision'))
          this.listLoading = false;
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        // if (j === 'realName' || j === 'mobile') {
        //   return dataMasking(v[j])
        // }
        return v[j]
      }))
    },
    getList() {
      this.listLoading = true;
      this.$store.dispatch('saveOrderDivisionPage', { path: this.$route.path, listQuery: this.listQuery });
      page(this.listQuery)
        .then(response => {
          if (response.status === 200) {
            response.data.records.forEach(item => {
              let re = /(?=(?!\b)(\d{3})+$)/g;
              let str = String(item.price)
              item.price =  str.replace(re, ',');
              let str2 = String(item.subEctionPrincipal)
              item.subEctionPrincipal =  str2.replace(re, ',');
              let str3 = String(item.repaymentOverduePenalty)
              item.repaymentOverduePenalty =  str3.replace(re, ',');
              let str4 = String(item.repaymentOverdueInterest)
              item.repaymentOverdueInterest =  str4.replace(re, ',');
            })
            this.expDis = false;
            this.listLoading = false;
            this.tableData = response.data.records;
            this.total = Number(response.data.total);
          }
        })
    },
    //查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    //重置
    reset() {
        this.listQuery.limit = 5;
        this.listQuery.page = 1;
        this.listQuery.orderId = "";
        this.listQuery.realName = "";
        this.listQuery.mobile = "";
        this.listQuery.sepaymentTimeStart = "";
        this.listQuery.sepaymentTimeEnd = "";
        this.listQuery.subAccountSatus = "";
        this.listQuery.channel = "";
    },
    //选中的数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    cancel() {
      this.dialogFormVisible = false
      this.partTable = {
        orderId: '',
        subEctionPrincipal: '',
        repaymentOverduePenalty: '',
        repaymentOverdueInterest: '',
        payWaterId: ''
      }
    },
    // 分账保存
    conserveFn() {
      if (this.partTable.subEctionPrincipal !== '' && this.partTable.repaymentOverduePenalty !== '' && this.partTable.repaymentOverdueInterest !== '') {
        let msg = this.price.replace(/,/g,'');
        let amount = null;
        amount = msg
        let val1 = Number(this.partTable.subEctionPrincipal)
        let val2 = Number(this.partTable.repaymentOverduePenalty)
        let val3 = Number(this.partTable.repaymentOverdueInterest)
        if (( val1 + val2 + val3 ) !== Number(amount)) {
          this.$message({
            showClose: true,
            message: this.$t('orderDivision.warn1'),
            type: 'warning'
          });
        } else {
          this.$confirm(this.$t('loanDetail.cue1'), {
            confirmButtonText: this.$t('btn.confirm'),
            cancelButtonText: this.$t('btn.cancel'),
            type: "warning",
            center: true
          })
          .then(() => {
            subAccount(this.partTable)
            .then(res => {
              if (res.status === 200) {
                this.$message({
                  showClose: true,
                  type: "info",
                  message: this.$t('loanDetail.cue2')
                });
                this.dialogFormVisible = false
                this.partTable = {
                  orderId: '',
                  subEctionPrincipal: '',
                  repaymentOverduePenalty: '',
                  repaymentOverdueInterest: '',
                  payWaterId: ''
                }
                this.getList()
              }
            })
          })
          .catch(() => {
            this.$message({
              showClose: true,
              type: "info",
              message: this.$t('loanDetail.cue3')
            });
          });
        }
      } else if (this.partTable.subEctionPrincipal === '') {
        this.$message({
          showClose: true,
          message: this.$t('orderDivision.ruleCapital'),
          type: 'warning'
        });
      } else if (this.partTable.repaymentOverduePenalty === '') {
        this.$message({
          showClose: true,
          message: this.$t('orderDivision.ruleInterest'),
          type: 'warning'
        });
      } else if (this.partTable.repaymentOverdueInterest === '') {
        this.$message({
          showClose: true,
          message: this.$t('orderDivision.ruleInterestRate'),
          type: 'warning'
        });
      }
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>

<style scoped lang='scss'>
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-right: 2.5%;
}
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before{
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px  0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
    div{
      width: 150px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px  0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
       width: 150px;
    }
  }
    .searchItem-overdue {
        display: flex;
        align-items: center;
        padding: 10px  0;
        div {
            width: 48px;
        }
    }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
}
.menu-list {
  padding: 20px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.part-table {
  width: 100%;
  display: flex;
  border: 1px solid #ccc;
  .part-item {
    flex: 1;
    text-align: center;
    border-right: 1px solid #ccc;
    &:last-child {
      border-right: 0;
    }
    div {
      width: 100%;
      line-height: 30px;
      &:nth-child(1) {
        border-bottom: 1px solid #ccc;
      }
    }
  }
}
.inp {
  border: none;
  outline: none;
  background: transparent;
  width: 100%;
  text-align: center;
}
.inp::-webkit-input-placeholder {
  font-size: 12px;
}
</style>